package com.personal.website.lottery.spider;

import java.sql.*;

/**
 * Created by 10171225 on 2016/2/17.
 */
public class DbAccessor {

    private SpiderProperties spiderProperties;
    public DbAccessor(SpiderProperties spiderProperties){
        this.spiderProperties = spiderProperties;
        try {
            Class.forName(this.spiderProperties.getJdbcDriver());
        } catch (ClassNotFoundException e) {
            System.out.println("Driver Class Found Error: " + e.getStackTrace().toString());
        }
    }

    private Connection getConnection(){
        Connection con = null;
        try {
            con = DriverManager.getConnection(spiderProperties.getJdbcUrl(),spiderProperties.getJdbcUsername(),spiderProperties.getJdbcPassword());
        } catch (SQLException e) {
            System.out.println("Get Connection Error: " + e.getStackTrace().toString());
        }
        return con;
    }


    public boolean exists(String sql)
    {
        System.out.println("sql: " + sql);
        Connection con = getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        boolean isExists = false;
        try {
            stmt = con.createStatement();
            stmt.setFetchSize(10000);
            rs = stmt.executeQuery(sql);
            rs.last();
            if(rs.getRow() >= 1){
                isExists = true;
            }
        } catch(SQLException e) {
            System.out.println("Exists Error: " + e.getStackTrace().toString());
        }finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (con != null) con.close();
            } catch(SQLException e) {
                System.out.println("Exists Release Error: " + e.getStackTrace().toString());
            }
        }
        return isExists;
    }

    public void execute(String sql)
    {
        System.out.println("sql: " + sql);
        Connection con = getConnection();
        Statement stmt = null;
        try {
            stmt = con.createStatement();
            stmt.execute(sql);
        } catch(SQLException e) {
            System.out.println("Execute Error: " + e.getStackTrace().toString());
        }
        finally {
            try {
                if (stmt != null) stmt.close();
                if (con != null) con.close();
            }
            catch(SQLException e) {
                System.out.println("Execute Release Error: " + e.getStackTrace().toString());
            }
        }
    }
}